#include "UTHScript.h"
#include "impl/JSCScript.h"
#include "kit.h"

namespace phnq
{
	namespace uth
	{
		static phnq::kit::log::Logger *log = phnq::kit::log::Logger::get("phnq::uth::UTHScript");

		static UTHValue* print(const void *userData, UTHArray *args)
		{
			for(int i=0; i<args->length(); i++)
			{
				if(i > 0)
					cout << " ";
			
				UTHValue *arg = args->get(i);
				if(arg->isString())
					cout << ((UTHString*)arg)->getChars();
				else
					cout << arg->toString();
				
				cout << endl;
			}
			return UTHUndefined::getInstance();
		}
	
		static UTHObject* addPrintFn(UTHObject *obj)
		{
			UTHFunction *printFn = new UTHFunction(print);
			obj->set("print", printFn);
			printFn->release();
			return obj;
		}

		UTHScript::UTHScript()
		{
			this->globals = addPrintFn(new UTHObject());
			this->execCount = 0;
		}

		UTHScript::~UTHScript()
		{
			if(this->globals)
				this->globals->release();
		}
	
		UTHScript* UTHScript::New(const char *code)
		{
			return new impl::JSCScript(code);
		}
	
		UTHObject* UTHScript::getGlobals()
		{
			return globals;
		}
	
		void UTHScript::setGlobals(UTHObject *globals)
		{
			if(this->globals)
				this->globals->release();
			
			if(globals)
			{
				this->globals = addPrintFn(globals);
				this->globals->retain();
			}
		}
		
		int UTHScript::getExecCount()
		{
			return execCount;
		}
		
		UTHValue* UTHScript::execute()
		{
			execCount++;
			return this->doExecute();
		}
	}
}
